
package site;

import constans.SizeConstans;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

public class DownloadRequest extends ProcessRequest {



    private final String folderFiles;



    public DownloadRequest(ServletContext context)
    {
        folderFiles = context.getInitParameter("FolderFiles");
    }


    @Override
    protected void process(HttpServletResponse response, String[] arguments)
    {

        String filename = arguments[0];

        ServletOutputStream outputStream = null;
        DataInputStream inputStream = null;

        try {

            outputStream = response.getOutputStream();

            File  f = new File(new File(folderFiles), filename);
            inputStream = new DataInputStream(new FileInputStream(f));

            response.setContentType("application/octet-stream");
            response.setContentLength((int) f.length());
            response.setHeader("Content-Disposition", "attachement; filename=" + filename + "");

            byte[] buffer = new byte[(int)SizeConstans.KByte];
            int length = 0;

            while ((length = inputStream.read(buffer)) != -1)
                outputStream.write(buffer, 0, length);
            outputStream.flush();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(DownloadRequest.class.getName()).log(Level.WARNING, null, ex.getMessage());
            response.setStatus(response.SC_NOT_FOUND);
        } catch (IOException ex) {
            Logger.getLogger(DownloadRequest.class.getName()).log(Level.WARNING, null, ex.getMessage());
        } finally{
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {}
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {}
        }
    }

}
